Maintaining bidirectional edges in undirected graphs
- In undirected graphs, every edge must be represented bidirectionally in adjacency lists. When adding edge {u,v}, you must insert v into u's neighbor list AND insert u into v's neighbor list. Forgetting either direction breaks the graph structure.
- The same principle applies to adjacency matrices: they must be symmetric with A[u,v] = A[v,u]. Setting only one direction creates an asymmetric matrix that represents a directed graph instead of the intended undirected one.
- Failing to maintain symmetry causes catastrophic errors: degree counts become incorrect, neighbor queries miss connections, and graph traversal algorithms like BFS/DFS may fail to reach all vertices or compute wrong results.
- The critical invariant to maintain is: "v ∈ adj[u] if and only if u ∈ adj[v]". This must hold after every add or remove operation. Writing explicit bidirectional code (not assuming it happens automatically) prevents this common bug that can silently corrupt your graph structure.